<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" draggable>


    <div v-if="userStore.user.username=='admin'">
<!--      @keyup.enter="submitHandle()-->
      <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="username" label="用户名">
              <el-input v-model="dataForm.username" placeholder="用户名"></el-input>
            </el-form-item>

            <el-form-item prop="orgId" label="所属机构">
              <el-tree-select
                  v-model="dataForm.orgId"
                  :data="orgList"
                  value-key="id"
                  check-strictly
                  @change="orgHandle($event)"
                  :render-after-expand="false"
                  :props="{ label: 'name', children: 'children' }"
                  style="width: 100%"
              />
            </el-form-item>
            <el-form-item prop="mobile" label="手机号">
              <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
            </el-form-item>
            <el-form-item prop="password" label="密码">
              <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
            </el-form-item>
            <el-form-item prop="postIdList" label="所属岗位">
              <el-select v-model="dataForm.postIdList" multiple placeholder="所属岗位" style="width: 100%">
                <el-option v-for="post in postList" :key="post.id" :label="post.postName" :value="post.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="realName" label="姓名">
              <el-input v-model="dataForm.realName" placeholder="姓名"></el-input>
            </el-form-item>
            <el-form-item prop="communityId" label="所属社区">
              <el-tree-select
                  v-model="dataForm.communityId"
                  :data="communityList"
                  value-key="id"
                  check-strictly
                  :render-after-expand="false"
                  :props="{ label: 'communityName', children: 'children' }"
                  style="width: 100%"
              />
            </el-form-item>
            <el-form-item prop="gender" label="性别">
              <fast-radio-group v-model="dataForm.gender" dict-type="user_gender"></fast-radio-group>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
              <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
            </el-form-item>
            <el-form-item prop="roleIdList" label="所属角色">
              <el-select v-model="dataForm.roleIdList" multiple placeholder="所属角色" style="width: 100%">
                <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div v-else>
      <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="username" label="用户名">
              <el-input v-model="dataForm.username" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item prop="orgId" label="所属机构">
              <el-tree-select
                  v-model="dataForm.orgId"
                  :data="orgList"
                  value-key="id"
                  @change="orgHandle($event)"
                  check-strictly
                  :render-after-expand="false"
                  :props="{ label: 'name', children: 'children' }"
                  style="width: 100%"
              />
            </el-form-item>
            <el-form-item prop="mobile" label="手机号">
              <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
            </el-form-item>
            <el-form-item prop="password" label="密码">
              <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
            </el-form-item>
            <el-form-item prop="postIdList" label="所属岗位">
              <el-select v-model="dataForm.postIdList" multiple placeholder="所属岗位" style="width: 100%">
                <el-option v-for="post in postList" :key="post.id" :label="post.postName" :value="post.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="realName" label="姓名">
              <el-input v-model="dataForm.realName" placeholder="姓名"></el-input>
            </el-form-item>
            <el-form-item prop="communityId" label="所属社区">
              <el-tree-select
                  v-model="dataForm.communityId"
                  :data="communityList"
                  value-key="id"
                  check-strictly
                  :render-after-expand="false"
                  :props="{ label: 'communityName', children: 'children' }"
                  style="width: 100%"
              />
            </el-form-item>
            <el-form-item prop="gender" label="性别">
              <fast-radio-group v-model="dataForm.gender" dict-type="user_gender"></fast-radio-group>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
              <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
            </el-form-item>
            <el-form-item prop="roleIdList" label="所属角色">
              <el-select v-model="dataForm.roleIdList" multiple placeholder="所属角色" style="width: 100%">
                <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>


		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import {useOrgListApi, useOrgMerchantApi} from '@/api/sys/orgs'
import { useUserApi, useUserSubmitApi } from '@/api/sys/user'
import {postMerchantOrgApi, usePostListApi} from '@/api/sys/post'
import {roleMerchantOrgApi, useRoleListApi} from '@/api/sys/role'
import {useUserStore} from "@/store/modules/user";
import {merchantListApi} from "@/api/sys/merchant";
import {orgCommunityListApi} from "@/api/new/community";


const userStore = useUserStore()

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const postList = ref<any[]>([])
const roleList = ref<any[]>([])
const orgList = ref([])
const communityList = ref([])
const dataFormRef = ref()
const merchantList = ref([])

const dataForm = reactive({
	id: '',
	username: '',
	realName: '',
	orgId: undefined,
	orgName: '',
	password: '',
	gender: 0,
	email: '',
  userType:1,
	mobile: '',
  communityId: '',
  merchantId: undefined,
  superAdmin: 0,
	roleIdList: [] as any[],
	postIdList: [] as any[],
	status: 1
})


const init = (id?: number) => {
	visible.value = true
	dataForm.id = ''

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
    orgList.value = []
    roleList.value = []
    postList.value = []
	}

	// id 存在则为修改
	if (id) {
		getUser(id)
	}

  if(userStore.user.username=='admin') {
    getMerchantList()
    getOrgList()
  }else{
    getOrgList()
    getPostList()
    getRoleList()
  }
}

// 获取岗位列表
const getPostList = () => {
	return usePostListApi().then(res => {
		postList.value = res.data
	})
}

// 获取角色列表
const getRoleList = () => {
	return useRoleListApi().then(res => {
		roleList.value = res.data
	})
}

// 获取机构列表
const getOrgList = () => {
	return useOrgListApi().then(res => {
		orgList.value = res.data
	})
}

// 获取信息
const getUser = (id: number) => {
	useUserApi(id).then(res => {
    Object.assign(dataForm, res.data)
    if (dataForm.orgId == '') {
      merchantHandle(dataForm.merchantId)
    } else {
      orgHandle(dataForm.orgId)
    }
	})
}

const dataRules = ref({
	username: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	realName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	mobile: [{ required: true, message: '必填项不能为空', trigger: 'blur' },
    { min: 11, max: 11, message: '手机号码不正确', trigger: 'blur' },]
	// orgId: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}

		useUserSubmitApi(dataForm).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}


// 获取商户列表
const getMerchantList = async () => {
  const res = await merchantListApi()
  merchantList.value = res.data
}


// 获取商户下机构列表
const getOrgMerchantList = (merchantId: number) => {
  useOrgMerchantApi(merchantId).then(res => {
    orgList.value = res.data
    console.log(orgList.value)
  })
}

const getOrgPostList = (orgId: any) => {
  const data = {
    orgId : orgId
  }
  postMerchantOrgApi(data).then(res => {
    postList.value = res.data
  })
}

const getMerchantPostList = (merchantId: any) => {
  const data = {
    merchantId : merchantId
  }
  postMerchantOrgApi(data).then(res => {
    postList.value = res.data
  })
}


const getMerchantRoleList = (merchantId: any) => {
  const data = {
    merchantId : merchantId
  }
  roleMerchantOrgApi(data).then(res => {
    roleList.value = res.data
  })
}

const getOrgRoleList = (orgId: any) => {
  const data = {
    orgId : orgId
  }
  roleMerchantOrgApi(data).then(res => {
    roleList.value = res.data
  })
}

const getOrgCommunityList = (orgId: any) => {
  const data = {
    orgId : orgId
  }
  orgCommunityListApi(data).then(res => {
    communityList.value = res.data
  })
}



const merchantHandle = (val: any) => {
  getOrgMerchantList(val)
  getMerchantPostList(val)
  getMerchantRoleList(val)
}

const orgHandle = (val: any) => {
  getOrgPostList(val)
  getOrgRoleList(val)
  getOrgCommunityList(val)
}

defineExpose({
	init
})
</script>
